﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.ComponentModel;
using System.Reflection;
using System.Net;
using System.Security;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Auth;
using Microsoft.Exchange.WebServices;
using System.IO;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using System.Xml;
using System.Web.Configuration;

namespace UCWebpart
{
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod(EnableSession = true)]
        public string getInstance()
        {
            try
            {
                string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;// "Data Source=mesdbsrv.gwkf.cn;Initial Catalog=VenueBooking;User ID=vbuser;Password=vb_2013";
                string sqlStr = "select * from [VenueBooking].[dbo].[MTR_instance]";
                return Worker.GetDataSet(sqlStr, conn).Tables[0].Rows[0][0].ToString();
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, Session["userName"].ToString());
                return "";
            }
        }

        [WebMethod(EnableSession = true)]
        public string updateInstanceByAdmin(string newInstance)
        {
            try
            {
                string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;// "Data Source=mesdbsrv.gwkf.cn;Initial Catalog=VenueBooking;User ID=vbuser;Password=vb_2013";
                string sqlStr = "delete from [VenueBooking].[dbo].[MTR_instance]";
                Worker.doSql(sqlStr, conn);
                string sqlInsert = string.Format(@"insert into [VenueBooking].[dbo].[MTR_instance] values ('{0}')", newInstance);
                Worker.doSql(sqlInsert, conn);
                return "更新成功";
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, Session["userName"].ToString());
                return ex.Message;
            }
        }

        [WebMethod(EnableSession = true)]
        public List<String> Init()
        {
            List<String> tlist = new List<String>();
            using (var mtr_resEn = new meetingroomManagementEntities()) {

                var cls = (from c in mtr_resEn.MTR_bas_Type where c.available
                           select 
                           c.Type).Distinct();
                foreach(var t in cls ){
                  tlist.Add(t.ToString());
                }
            return tlist;
            }
        }

        [WebMethod(EnableSession = true)]
        public string layout() {
            Session["userName"] = null;
            Session["userInfo"] = null;
            return "退出成功";
        }

        [WebMethod(EnableSession = true)]
        public string GoNext(DateTime startTime, DateTime endTime, string mtrName)
        {
            using (var mtr_resEn = new meetingroomManagementEntities())
            {
                MTR_bas_BookingManage mtrBM1 = new MTR_bas_BookingManage();
                mtrBM1.bookingID = "1026";
                mtrBM1.bookingTime = Convert.ToDateTime(startTime);
                //mtrBM1.endTime = Convert.ToDateTime(endTime);
                mtrBM1.Meetingroom = Convert.ToInt32(mtrName); //去掉最右边的#号 mtrName.Remove(mtrName.Length-1,1)
                mtr_resEn.MTR_bas_BookingManage.Add(mtrBM1);
                mtr_resEn.SaveChanges();

                var cls = (from c in mtr_resEn.MTR_bas_BookingManage
                           where c.bookingID == "1025"
                           select c).SingleOrDefault<MTR_bas_BookingManage>();
                if (cls == null)
                {
                    return null;
                }
                else
                    return "ok";
            }
        }

        [WebMethod(EnableSession = true)]
        public string[] getEmails()
        {
            if (Application["EmailAddress"] == null)
            {
                Application["EmailAddress"] = Worker.getEmail();
            }
            List<String> EmailList = (List<String>)Application["EmailAddress"];
            string[] eList = new string[EmailList.Count];
            for (int i = 0; i < EmailList.Count; i++) {
                eList[i] = EmailList[i];
            }
            return eList;
        }

        [WebMethod(EnableSession = true)]
        public string[] getNameAndEmails()
        {
            if (Application["NameAndEmails"] == null) 
            {
                Application["NameAndEmails"] = Worker.getNameAndEmail();
            }
            string[] NameAndEmailList = (string[])Application["NameAndEmails"];
            return NameAndEmailList;
        }

        [WebMethod(EnableSession = true)]
        public List<string> checkEmail(string startString)
        {
            if (Application["EmailAddress"] == null) {
                Application["EmailAddress"] = Worker.getEmail();
            }
             List<String> EmailList = (List<String>)Application["EmailAddress"];

             List<string> lstTmp = new List<string>();
            ((List<String>)Application["EmailAddress"]).Select(p => p.ToString()).ToList().ForEach(q =>
             {
                 if (q.StartsWith(startString))
                     lstTmp.Add(q);
             });
            return lstTmp;
        }

        [WebMethod(EnableSession = true)]
        public string Lock(int meetingRoomNo, string startDate, string startTime, string endDate, string endTime, string weeks)
        {
            //锁定一次
            if (weeks.Length <= 1) {
               return OnetimeLock(meetingRoomNo, startDate, startTime, endDate, endTime);
            }
            //周期锁定
            else 
            {
                return PeriodicLock(meetingRoomNo, startDate, startTime, endDate, endTime, weeks);
            }
        }


        [WebMethod(EnableSession = true)]
        public string Booking(string participants, string btnId, string meetingTheme, string bookingVIP, string meetingAbstract, string phoneNo,
            string cc,
            int meetingRoomNo, string mtrName, string specialRequestFirst, string specialRequestSecond,
            string startDate, string startTime, string endDate, string endTime, string userName, string weeks, string passWord)
        {
            try
            {
                string results = "";

                DateTime st = DateTime.Parse(startDate + " " + startTime);  //会议开始时间
                DateTime et = DateTime.Parse(endDate + " " + endTime);      //会议结束时间
                DateTime timeNow = DateTime.Now;

                if (st < timeNow)
                {
                    return "您预定的时间早于当前时间，请重新选择活动开始时间";
                }
                string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;
                string getVIPByID = "select mtrType, mtrAddress + mtrAddress1 +' '+ mtrName from  [VenueBooking].[dbo].[MTR_bas_Meetingroom] where mtrId = " + meetingRoomNo;
                DataTable dt = Worker.GetDataSet(getVIPByID, conn).Tables[0];
                bookingVIP = dt.Rows[0][0].ToString();
                string mtrAdd = dt.Rows[0][1].ToString();
                //本次是单次预定
                if (weeks.Length < 1)
                {
                    if (startDate != endDate)
                    {
                        return "您的选择跨天，请重新选择或联系管理员周期预定";
                    }
                    if (checkConflict(meetingRoomNo, startDate, startTime, endDate, endTime) != "")
                    {
                        return checkConflict(meetingRoomNo, startDate, startTime, endDate, endTime);
                    }
                    //和周期冲突检测
                    else
                    {
                        if (checkOnceWithPeriodicConflict(meetingRoomNo, startDate, startTime, endDate, endTime) != "")
                        {
                            return checkOnceWithPeriodicConflict(meetingRoomNo, startDate, startTime, endDate, endTime);
                        }
                    }
                }
                //本次是周期性预定
                if (weeks.Length > 1)
                {

                    if (checkPeriodicConflict(meetingRoomNo, startDate, startTime, weeks, endDate, endTime) != "")
                    {
                        return checkPeriodicConflict(meetingRoomNo, startDate, startTime, weeks, endDate, endTime);
                    }
                }
                if (btnId == "lock")
                {
                    results = Lock(meetingRoomNo, startDate, startTime, endDate, endTime, weeks);
                    return results;
                }
                else
                {
                    int OncelongestHour = 0; //每次最多订多长时间
                    int LongestAdvanceBookingDay = 0;//最多提前多久订
                    int mtrNo = meetingRoomNo;
                    TimeSpan ts1 = new TimeSpan(st.Ticks);
                    TimeSpan ts2 = new TimeSpan(et.Ticks);
                    string dateDiff = null;
                    TimeSpan ts = ts1.Subtract(ts2).Duration();
                    //显示时间  
                    dateDiff = ts.Days.ToString() + "天"
                            + ts.Hours.ToString() + "小时"
                            + ts.Minutes.ToString() + "分钟"
                            + ts.Seconds.ToString() + "秒";
                    TimeSpan ts3 = new TimeSpan(timeNow.Ticks);

                    TimeSpan tsn = ts3.Subtract(ts2).Duration();//提前预定的天数

                    string dateDiff1 = tsn.Days.ToString() + "天"
                            + tsn.Hours.ToString() + "小时"
                            + tsn.Minutes.ToString() + "分钟"
                            + tsn.Seconds.ToString() + "秒";
                    using (meetingroomManagementEntities mtrmEntities = new meetingroomManagementEntities())
                    {
                        //查询会议室对应的会议室资源
                        var cls = (from c in mtrmEntities.MTR_bas_Meetingroom
                                   where c.mtrId == mtrNo
                                   select c).SingleOrDefault<MTR_bas_Meetingroom>();
                        OncelongestHour = Convert.ToInt32(cls.mtrLongestBookingDay);
                        LongestAdvanceBookingDay = Convert.ToInt32(cls.mtrLongestAdvanceBookingTime);
                    }
                    //周期预定
                    if (weeks.Length > 1)
                    {
                        results = PeriodicBookingSuccess(participants, cc, meetingTheme, meetingAbstract, phoneNo, mtrAdd, mtrNo, specialRequestFirst,
                         specialRequestSecond, st, et, startDate, startTime, endDate, endTime, userName, weeks, passWord);
                    }
                    //开启审批流程
                    else if (st.DayOfWeek.ToString() == "Saturday" || st.DayOfWeek.ToString() == "Sunday" || ts.Hours >= OncelongestHour
                        || (tsn.Days >= LongestAdvanceBookingDay) || bookingVIP == "VIP")
                    {
                        //存入数据库
                        results = ApproveBooking(participants, cc, meetingTheme, meetingAbstract, phoneNo, mtrAdd, mtrNo, specialRequestFirst,
                        specialRequestSecond, st, et, startDate, startTime, endDate, endTime, userName, weeks);
                    }
                    //满足自助预定条件 && weeks.Length <= 1 
                    else if ((LongestAdvanceBookingDay > tsn.Days && ts.Hours < OncelongestHour && bookingVIP == "普通"))//
                    {
                        results = SelfBookingSuccess(participants, cc, meetingTheme, meetingAbstract, phoneNo, mtrAdd, mtrNo, specialRequestFirst,
                         specialRequestSecond, st, et, startDate, startTime, endDate, endTime, userName, weeks);
                    }
                    return results;
                }
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, "booking");
                return ex.Message.ToString();
            }
        }
        /*
         * ts timeSpan类型，时间差
         */
        /// <summary>
        /// 字符串转成时间 计算时间差
        /// </summary>
        /// <param name="st">st 开始时间的字符串形式 yyyy-MM-dd hh-mm-ss</param>
        /// <param name="et">et 结束时间的字符串形式 yyyy-MM-dd hh-mm-ss</param>
        /// <returns>dateDiff 返回的字符串类型</returns>
        public string timeDiffer(string st, string et)
        {
            DateTime sst = DateTime.Parse(st);
            DateTime eet = DateTime.Parse(et);
            //if(startDate==endDate && ){}
            string dateDiff = null;
            TimeSpan ts1 = new TimeSpan(sst.Ticks);
            TimeSpan ts2 = new TimeSpan(eet.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            //显示时间  
            dateDiff = ts.Days.ToString() + "天"
                    + ts.Hours.ToString() + "小时"
                    + ts.Minutes.ToString() + "分钟"
                    + ts.Seconds.ToString() + "秒";
            return dateDiff;
        }

        /// <summary>
        /// 开启审批流程
        /// </summary>
        /// <param name="participants">与会人</param>
        /// <param name="meetingTheme">主题</param>
        /// <param name="meetingAbstract">简介</param>
        /// <param name="mtrAdd">地址</param>
        /// <param name="mtrNo">编号</param>
        /// <param name="specialRequestFirst">特殊要求一</param>
        /// <param name="specialRequestSecond">特殊要求二</param>
        /// <param name="st"></param>
        /// <param name="et"></param>
        /// <param name="startDate">开始日期</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="weeks">星期</param>
        /// <returns></returns>
        public string ApproveBooking(string participants,string cc, string meetingTheme, 
            string meetingAbstract, string phoneNo,string mtrAdd, int mtrNo, string specialRequestFirst,
                string specialRequestSecond, DateTime st, DateTime et, string startDate,
            string startTime, string endDate, string endTime,string userName, string weeks)
        {
            string ss = "";
            using (meetingroomManagementEntities mtr_BookingSuc = new meetingroomManagementEntities())
            {
                MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
                MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
                string keyId = Guid.NewGuid().ToString();
                var approveUrl = @"http://SZSPWEB02:2015/VenueBooking/WEB/ShowInfor.aspx?id=" + keyId + @"&isApprove=isApprove";
                //var approveUrl = @"http://workflow.kaifa.cn:2015/VenueBooking/WEB/ShowInfor.aspx?id=" + keyId + @"&isApprove=isApprove";
                string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;// "Data Source=mesdbsrv.gwkf.cn;Initial Catalog=VenueBooking;User ID=vbuser;Password=vb_2013";
                string strSql = string.Format(@"select [undefine3] from [VenueBooking].[dbo].[MTR_bas_Meetingroom] where mtrId ={0}", mtrNo);
                DataTable dt = Worker.GetDataSet(strSql, conn).Tables[0];
                string leadship = "";
                for (int i = 0; i < dt.Rows.Count; i++) 
                {
                    leadship += @"gwkf\" + dt.Rows[i][0].ToString() + ";";
                }
                string ApproveId = string.Empty;
                
                try
                {
                    ApproveId = startApprove(userName, approveUrl, leadship);
                }
                catch (Exception e)
                {
                    Worker w = new Worker();
                    w.writeErrorMessage("0", e, "ApproveBooking");
                    return "开启审批流失败" + e.Message;
                }
                string[] weekdays = weeks.Split(',');
                //单次预定审批
                if (weekdays.Length <= 1)
                {
                    mtrBS.isPeriodic = false;
                    mtrBM.bookingID = keyId;
                    mtrBM.bookingType = "待审批";
                    mtrBM.Meetingroom = mtrNo;
                    mtrBM.bookingPerson = userName;
                    mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                    mtrBM.meetingTheme = meetingTheme;
                    mtrBM.participants = participants;
                    mtrBM.meetingAbstract = meetingAbstract;
                    mtrBM.specialRequestFirst = specialRequestFirst;
                    mtrBM.specialRequestSecond = specialRequestSecond;
                    mtrBM.bookingState = 1;
                    mtrBM.undefine1 = Session["orgType1"].ToString();
                    mtrBM.undefine2 = Session["orgType3"].ToString();
                    mtrBM.useResult = 0;
                    mtrBM.undefine3 = ApproveId;
                    mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
                    mtrBS.Monday = false;
                    mtrBS.Tuesday = false;
                    mtrBS.Wednesday = false;
                    mtrBS.Thursday = false;
                    mtrBS.Friday = false;
                    mtrBS.Saturday = false;
                    mtrBS.Sunday = false;
                    mtrBS.planId = keyId;
                    mtrBS.meetingRoom = mtrNo;
                    mtrBS.undefine2 = phoneNo;
                    mtrBS.undefine3 = cc;
                    mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                    mtrBS.startTime = startTime;
                    mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                    mtrBS.endTime = endTime;
                    mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                    mtr_BookingSuc.MTR_bas_BookingSchedul.Add(mtrBS);
                    try
                    {

                        mtr_BookingSuc.Configuration.ValidateOnSaveEnabled = false;
                        mtr_BookingSuc.SaveChanges();
                        mtr_BookingSuc.Configuration.ValidateOnSaveEnabled = true;
                        ss = "进入审批流程，请等待签批";
                    }
                    catch (Exception ex)
                    {
                        Worker w = new Worker();
                        w.writeErrorMessage("0", ex, "ApproveBooking1");
                        ss = ex.Message;
                    }
                }
            }
            return ss;
        }
                //#region
                ////周期预定审批
                //if (weekdays.Length > 1)
                //{
                //    mtrBS.isPeriodic = true;
                //    mtrBM.bookingID = keyId;
                //    mtrBM.bookingType = "待审批";
                //    mtrBM.Meetingroom = mtrNo;
                //    mtrBM.bookingPerson = userName;
                //    mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                //    mtrBM.meetingTheme = meetingTheme;
                //    mtrBM.participants = participants;
                //    mtrBM.meetingAbstract = meetingAbstract;
                //    mtrBM.specialRequestFirst = specialRequestFirst;
                //    mtrBM.specialRequestSecond = specialRequestSecond;
                //    mtrBM.bookingState = 1;//状态为预定成功
                //    mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
                //    mtr_BookingSuc.SaveChanges();
                //    foreach (string weekday in weekdays)
                //    {
                //        //mtrBS.(weekday.ToString())=weekday;
                //        if (weekday == "Monday") mtrBS.Monday = true;
                //        else if (weekday == "Tuesday") mtrBS.Tuesday = true;
                //        else if (weekday == "Wednesday") mtrBS.Wednesday = true;
                //        else if (weekday == "Thursday") mtrBS.Thursday = true;
                //        else if (weekday == "Friday") mtrBS.Friday = true;
                //        else if (weekday == "Saturday") mtrBS.Saturday = true;
                //        else if (weekday == "Sunday") mtrBS.Sunday = true;
                //    }
                //    mtrBS.planId = keyId;
                //    mtrBS.meetingRoom = mtrNo;
                //    mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                //    mtrBS.startTime = startTime;
                //    mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                //    mtrBS.endTime = endTime;
                //    mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                //    mtr_BookingSuc.MTR_bas_BookingSchedul.Add(mtrBS);
                //    mtr_BookingSuc.SaveChanges();
                //}
                //#endregion
        /// <summary>
        /// 单次冲突检测(单次，周期)
        /// </summary>
        /// <param name="meetingRoomNo"></param>
        /// <param name="startDate"></param>
        /// <param name="startTime"></param>
        /// <param name="endDate"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public string checkConflict(int meetingRoomNo, string startDate, string startTime, string endDate, string endTime)
        {
            try
            {
                DateTime sd = DateTime.Parse(startDate);
                DateTime st = DateTime.Parse(startDate + " " + startTime);   //会议开始时间
                DateTime et = DateTime.Parse(endDate + " " + endTime);       //会议结束时间
                using (var mme = new meetingroomManagementEntities())
                {
                    var query = (from bm in mme.MTR_bas_BookingManage
                                 join bs in mme.MTR_bas_BookingSchedul
                                     on bm.bookingID equals bs.planId
                                 where bm.Meetingroom == meetingRoomNo && bs.isPeriodic == false
                                 && bs.meetingStartDate >= sd && (bm.bookingState == 1 || bm.bookingState == 2 || bm.bookingState == 3)
                                 select new
                                 {
                                     ssd = bs.meetingStartDate,
                                     sst = bs.startTime,
                                     sed = bs.meetingEndDate,
                                     set = bs.endTime,
                                 }).ToList();
                    foreach (var q in query)
                    {
                        DateTime mst = DateTime.Parse(q.ssd.Value.ToLongDateString() + " " + q.sst);
                        DateTime met = DateTime.Parse(q.sed.Value.ToLongDateString() + " " + q.set);
                        if (mst < et && mst > st)
                        {
                            return "系统检测到与已存在的预定发生冲突";
                        }
                        if (st < met && et >= met)
                        {
                            return "系统检测到与已存在的预定发生冲突";
                        }
                        if (mst <= st && et <= met)
                        {
                            return "系统检测到与已存在的预定发生冲突";
                        }
                        if (mst > st && et > met)
                        {
                            return "系统检测到与已存在的预定发生冲突";
                        }
                    }
                }
                return "";
            }
            catch (Exception ex) {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, "checkConflict");
                return ex.Message;
            }
        }
        /// <summary>
        /// 条件满足，完成自助预定
        /// </summary>
        /// <param name="participants"></param>
        /// <param name="meetingTheme"></param>
        /// <param name="meetingAbstract"></param>
        /// <param name="mtrAdd"></param>
        /// <param name="mtrNo"></param>
        /// <param name="specialRequestFirst"></param>
        /// <param name="specialRequestSecond"></param>
        /// <param name="st"></param>
        /// <param name="et"></param>
        /// <param name="startDate"></param>
        /// <param name="startTime"></param>
        /// <param name="endDate"></param>
        /// <param name="endTime"></param>
        /// <param name="weeks"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public string SelfBookingSuccess(string participants,string cc,string meetingTheme, string meetingAbstract, string phoneNo,
            string mtrAdd, int mtrNo, string specialRequestFirst,string specialRequestSecond, DateTime st, DateTime et,
            string startDate, string startTime, string endDate, string endTime,string userName, string weeks)
        {
            try
            {
                using (meetingroomManagementEntities mtr_BookingSuc = new meetingroomManagementEntities())
                {
                    MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
                    MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
                    string keyId = Guid.NewGuid().ToString();
                    string[] weekdays = weeks.Split(',');
                    //单次自助预定
                    if (weekdays.Length <= 1)
                    {
                        mtrBS.isPeriodic = false;
                        mtrBM.bookingID = keyId;
                        mtrBM.bookingType = "自助";
                        mtrBM.Meetingroom = mtrNo;
                        mtrBM.bookingPerson = userName;
                        mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                        mtrBM.meetingTheme = meetingTheme;
                        mtrBM.participants = participants;
                        mtrBM.meetingAbstract = meetingAbstract;
                        mtrBM.specialRequestFirst = specialRequestFirst;
                        mtrBM.specialRequestSecond = specialRequestSecond;
                        mtrBM.bookingState = 2;
                        mtrBM.undefine1 = Session["orgType1"].ToString();
                        mtrBM.undefine2 = Session["orgType3"].ToString();
                        mtrBM.undefine3 = "0";
                        mtrBM.useResult = 0;
                        mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
                        mtrBS.Monday = false;
                        mtrBS.Tuesday = false;
                        mtrBS.Wednesday = false;
                        mtrBS.Thursday = false;
                        mtrBS.Friday = false;
                        mtrBS.Saturday = false;
                        mtrBS.Sunday = false;
                        mtrBS.planId = keyId;
                        mtrBS.meetingRoom = mtrNo;
                        mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                        mtrBS.startTime = startTime;
                        mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                        mtrBS.endTime = endTime;
                        mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                        mtrBS.undefine2 = phoneNo;
                        mtrBS.undefine3 = cc;
                        mtr_BookingSuc.MTR_bas_BookingSchedul.Add(mtrBS);

                        string[] attendees = participants.Split(';');
                        string[] ccs = cc.Split(';');
                        Worker w = new Worker();
                        string body = meetingAbstract;
                        mtr_BookingSuc.Configuration.ValidateOnSaveEnabled = false;
                        int k = mtr_BookingSuc.SaveChanges();
                        mtr_BookingSuc.Configuration.ValidateOnSaveEnabled = true;
                        string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;
                        string check = "select 1 FROM [VenueBooking].[dbo].[MTR_bas_BookingManage] where bookingID='" + keyId + "'";
                        if (Worker.GetDataSet(check, conn).Tables[0].Rows.Count == 1)
                        {
                            w.SendMeetingRequest(st, et, mtrAdd, meetingTheme, body, attendees, ccs,
                                keyId, false, userName, userName + "@kaifa.cn", false, "");
                        }
                        else {
                            //string insertSQL = "insert into [VenueBooking].[dbo].[MTR_bas_BookingManage] ";
                        }
                    }
                }
                return "恭喜您，自助预定成功";
            }
            catch (Exception e)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", e, Session["userName"].ToString());
                return e.Message;
            }
        }
        [WebMethod(EnableSession = true)]
        private string OnetimeLock(int meetingRoomNo, string startDate, string startTime, string endDate, string endTime)
        {
            try
            {
                using (meetingroomManagementEntities mtr_BookingSuc = new meetingroomManagementEntities())
                {
                    MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
                    MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
                    string keyId = Guid.NewGuid().ToString();
                    //单次锁定
                    mtrBS.isPeriodic = false;
                    mtrBM.bookingID = keyId;
                    mtrBM.bookingType = "管理员锁定";
                    mtrBM.Meetingroom = meetingRoomNo;
                    mtrBM.bookingPerson = Session["userName"].ToString();
                    mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                    mtrBM.meetingTheme = "lock";
                    mtrBM.participants = "";
                    mtrBM.meetingAbstract = "";
                    mtrBM.specialRequestFirst = "";
                    mtrBM.specialRequestSecond = "";
                    mtrBM.bookingState = 3;
                    mtrBM.undefine1 = Session["orgType1"].ToString();
                    mtrBM.undefine2 = Session["orgType3"].ToString();
                    mtrBM.undefine3 = null;
                    mtrBM.useResult = 0;
                    mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
                    mtrBS.Monday = null;
                    mtrBS.Tuesday = null;
                    mtrBS.Wednesday = null;
                    mtrBS.Thursday = null;
                    mtrBS.Friday = null;
                    mtrBS.Saturday = null;
                    mtrBS.Sunday = null;
                    mtrBS.undefine3 = "";
                    mtrBS.planId = keyId;
                    mtrBS.meetingRoom = meetingRoomNo;
                    mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                    mtrBS.startTime = startTime;
                    mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                    mtrBS.endTime = endTime;
                    mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                    mtr_BookingSuc.MTR_bas_BookingSchedul.Add(mtrBS);
                    int k = mtr_BookingSuc.SaveChanges();
                }
                return "锁定成功";
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, Session["userName"].ToString());
                return ex.Message;
            }
        }

        string error;
        [WebMethod]
        private bool checkAD(string adPath, string domainName, string AD_AccountNo, string AD_Password)
        {
            LdapAuthentication adAuth = new LdapAuthentication(adPath);
            //自己寫的類別檔。
            try
            {
                return adAuth.IsAuthenticated(domainName, AD_AccountNo, AD_Password);
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, Session["userName"].ToString());
                error = ex.Message;
                return false;
            }
        }

        public string CheckUser(string userName, string pwd)
        {
            string AD_AccountNo = userName;
            string AD_Password = pwd;
            //在这里校验AD用户及密码
            string domainName = "GWKF";
            string adPath = "LDAP://" + domainName;

            if (checkAD(adPath, domainName, AD_AccountNo, AD_Password))
            {
                return "Succsee";
            }
            else return error;
            //return "xxx";
        }

        /// <summary>
        /// 周期性预定
        /// </summary>
        /// <param name="participants"></param>
        /// <param name="meetingTheme"></param>
        /// <param name="meetingAbstract"></param>
        /// <param name="mtrAdd"></param>
        /// <param name="mtrNo"></param>
        /// <param name="specialRequestFirst"></param>
        /// <param name="specialRequestSecond"></param>
        /// <param name="st"></param>
        /// <param name="et"></param>
        /// <param name="startDate"></param>
        /// <param name="startTime"></param>
        /// <param name="endDate"></param>
        /// <param name="endTime"></param>
        /// <param name="weeks"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public string PeriodicBookingSuccess(string participants, string cc, string meetingTheme, string meetingAbstract, string phoneNo, string mtrAdd, int mtrNo, string specialRequestFirst,
              string specialRequestSecond, DateTime st, DateTime et, string startDate, string startTime, string endDate, string endTime, string userName, string weeks, string passWord)
        {
            if (CheckUser(userName, passWord) != "Succsee")
            {
                return "您输入在密码错误";
            }

            string otp = checkOnceConflict(mtrNo, startDate, startTime, weeks, endDate, endTime);
            string ptp = checkPeriodicConflict(mtrNo, startDate, startTime, weeks, endDate, endTime);
            if (otp.Length > 1 || ptp.Length > 1) return otp + ptp;
            using (var mtr_BookingSuc = new meetingroomManagementEntities())
            {
                MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
                MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
                string keyId = Guid.NewGuid().ToString();
                string[] weekdays = weeks.Split(',');

                string[] wek = new string[weekdays.Length - 1];

                for (int k = 0; k < weekdays.Length - 1; k++)
                {
                    wek[k] = weekdays[k];
                }
                mtrBS.isPeriodic = true;
                mtrBM.bookingID = keyId;
                mtrBM.bookingType = "管理员预定";
                mtrBM.Meetingroom = mtrNo;
                mtrBM.bookingPerson = Session["userName"].ToString();
                mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                mtrBM.meetingTheme = meetingTheme;
                mtrBM.participants = participants;
                mtrBM.meetingAbstract = meetingAbstract;
                mtrBM.specialRequestFirst = specialRequestFirst;
                mtrBM.specialRequestSecond = specialRequestSecond;
                mtrBM.bookingState = 2;//状态为预定成功
                mtrBM.undefine1 = Session["orgType1"].ToString();
                mtrBM.undefine2 = Session["orgType3"].ToString();
                mtrBM.useResult = 0;
                mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);

                mtrBS.Monday = false;
                mtrBS.Tuesday = false;
                mtrBS.Wednesday = false;
                mtrBS.Thursday = false;
                mtrBS.Friday = false;
                mtrBS.Saturday = false;
                mtrBS.Sunday = false;
                foreach (string weekday in weekdays)
                {
                    if (weekday == "Monday") mtrBS.Monday = true;
                    else if (weekday == "Tuesday") mtrBS.Tuesday = true;
                    else if (weekday == "Wednesday") mtrBS.Wednesday = true;
                    else if (weekday == "Thursday") mtrBS.Thursday = true;
                    else if (weekday == "Friday") mtrBS.Friday = true;
                    else if (weekday == "Saturday") mtrBS.Saturday = true;
                    else if (weekday == "Sunday") mtrBS.Sunday = true;
                }
                mtrBS.planId = keyId;
                mtrBS.meetingRoom = mtrNo;
                mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                mtrBS.startTime = startTime;
                mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                mtrBS.endTime = endTime;
                mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                mtrBS.undefine2 = phoneNo;
                mtrBS.undefine3 = cc;
                mtr_BookingSuc.MTR_bas_BookingSchedul.Add(mtrBS);
                try
                {
                    //发送邮件
                    Worker w = new Worker();
                    w.sendPeriodicMeetingMessage(keyId, userName, participants, cc, meetingTheme, meetingAbstract, mtrAdd, mtrNo, specialRequestFirst,
                  specialRequestSecond, st, et, startDate, startTime, endDate, endTime, wek, passWord);
                }
                catch (Exception ex)
                {
                    Worker w = new Worker();
                    w.writeErrorMessage("0", ex, Session["userName"].ToString());
                    return ex.Message;
                }
                mtr_BookingSuc.Configuration.ValidateOnSaveEnabled = false;
                int kk = mtr_BookingSuc.SaveChanges();
                mtr_BookingSuc.Configuration.ValidateOnSaveEnabled = true;
            }
            return "恭喜您，周期预定成功";
        }
        [WebMethod(EnableSession=true)]
        private string PeriodicLock(int meetingRoomNo, string startDate, string startTime, string endDate, string endTime, string weeks)
        {
            string otp = checkOnceConflict(meetingRoomNo, startDate, startTime, weeks, endDate, endTime);
            string ptp = checkPeriodicConflict(meetingRoomNo, startDate, startTime, weeks, endDate, endTime);
            if (otp.Length > 1 || ptp.Length > 1) return otp + ptp;
            try
            {
                using (var mtr_BookingSuc = new meetingroomManagementEntities())
                {
                    MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
                    MTR_bas_BookingSchedul mtrBS = new MTR_bas_BookingSchedul();
                    string keyId = Guid.NewGuid().ToString();
                    string[] weekdays = weeks.Split(',');
                    mtrBS.isPeriodic = true;
                    mtrBM.bookingID = keyId;
                    mtrBM.bookingType = "管理员锁定";
                    mtrBM.Meetingroom = meetingRoomNo;
                    mtrBM.bookingPerson = Session["userName"].ToString();
                    mtrBM.bookingTime = DateTime.Now;  //保存预定时间
                    mtrBM.meetingTheme = "";
                    mtrBM.participants = "";
                    mtrBM.meetingAbstract = "";
                    mtrBM.specialRequestFirst = "";
                    mtrBM.specialRequestSecond = "";
                    mtrBM.bookingState = 2;//状态为预定成功
                    mtrBM.undefine1 = Session["orgType1"].ToString();
                    mtrBM.undefine2 = Session["orgType1"].ToString();
                    mtrBM.useResult = 0;

                    mtr_BookingSuc.MTR_bas_BookingManage.Add(mtrBM);
                    mtr_BookingSuc.SaveChanges();
                    foreach (string weekday in weekdays)
                    {
                        //mtrBS.(weekday.ToString())=weekday;
                        if (weekday == "Monday") mtrBS.Monday = true;
                        else if (weekday == "Tuesday") mtrBS.Tuesday = true;
                        else if (weekday == "Wednesday") mtrBS.Wednesday = true;
                        else if (weekday == "Thursday") mtrBS.Thursday = true;
                        else if (weekday == "Friday") mtrBS.Friday = true;
                        else if (weekday == "Saturday") mtrBS.Saturday = true;
                        else if (weekday == "Sunday") mtrBS.Sunday = true;
                    }
                    mtrBS.planId = keyId;
                    mtrBS.meetingRoom = meetingRoomNo;
                    mtrBS.meetingStartDate = Convert.ToDateTime(startDate);
                    mtrBS.startTime = startTime;
                    mtrBS.meetingEndDate = Convert.ToDateTime(endDate);
                    mtrBS.endTime = endTime;
                    mtrBS.undefine1 = timeDiffer((startDate + " " + mtrBS.startTime), (endDate + " " + mtrBS.endTime));
                    mtr_BookingSuc.MTR_bas_BookingSchedul.Add(mtrBS);
                    mtr_BookingSuc.SaveChanges();
                }
                return "锁定成功";
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, Session["userName"].ToString());
                return ex.Message;
            }
        }
        //传递到WorkFlow
        public string startApprove(string applicant, string weburl, string leadship)
        {
            WFBookingManage.WFWebserviceClient wfb = new WFBookingManage.WFWebserviceClient();
            string xml = createXml(applicant, weburl, leadship);
            string erro = string.Empty;
            string sguid = wfb.StartWF(out erro, 33300000, xml, null);
            if (sguid == string.Empty)
            {
                return "审批流开启失败";
            }
            return sguid;
        }

        public string createXml(string applicant, string weburl, string leadship)
        {
            return GenerateXMLFile(applicant, weburl,leadship);
        }
        public string GenerateXMLFile(string applicant, string weburl,string leadship)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                //根节点
                XmlElement rootElement = xmlDoc.CreateElement("EFlowsConfigXML");
                xmlDoc.AppendChild(rootElement);
                //第一层第一个
                XmlElement firstLevelElemet1 = xmlDoc.CreateElement("WFParameters");
                firstLevelElemet1.SetAttribute("Description", "运行时候的配置参数");
                rootElement.AppendChild(firstLevelElemet1);
                //第二层第一个
                XmlElement secondLevelElemet1 = xmlDoc.CreateElement("WFParameter");
                //secondLevelElemet1.SetAttribute("Description", "申请人");
                secondLevelElemet1.SetAttribute("name", "WFApplyBy");
                secondLevelElemet1.SetAttribute("Value", applicant);
                firstLevelElemet1.AppendChild(secondLevelElemet1);
                //第二层第二个
                XmlElement secondLevelElemet2 = xmlDoc.CreateElement("WFParameter");
                //secondLevelElemet2.SetAttribute("Description", "审批内容页面链接URL");
                secondLevelElemet2.SetAttribute("name", "WFContentURL");
                secondLevelElemet2.SetAttribute("Value", weburl);
                firstLevelElemet1.AppendChild(secondLevelElemet2);
                //第一层第二个
                XmlElement firstLevelElemet2 = xmlDoc.CreateElement("StaticColumns");
                //firstLevelElemet2.SetAttribute("Description", "用于查询检索的列");
                rootElement.AppendChild(firstLevelElemet2);
                XmlElement secondLevelElemet3 = xmlDoc.CreateElement("StaticColumn");
                secondLevelElemet3.SetAttribute("name", "LeaderShip");
                secondLevelElemet3.SetAttribute("Value", leadship);
                firstLevelElemet2.AppendChild(secondLevelElemet3);
                //XmlElement firstLevelElement3 = xmlDoc.CreateElement("DynamicColumns");
                //rootElement.AppendChild(firstLevelElement3);
                //XmlElement secondLevelElemet4 = xmlDoc.CreateElement("DynamicColumn");
                //secondLevelElemet4.SetAttribute("name", "ColumnName");
                //secondLevelElemet4.SetAttribute("Value", "ColumnValue");
                //firstLevelElement3.AppendChild(secondLevelElemet4);
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, "createXml");
            }
            return xmlDoc.InnerXml;
        }

        public void testMeeting()
        {
            //#region 发送邮件代码
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.TraceEnabled = true;
                service.Credentials = new NetworkCredential("mespublisher", "mes_2011", "kaifa.cn");
                service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                service.UseDefaultCredentials = true;

                //service.AutodiscoverUrl("shengweihu@kaifa.cn");//程序可以自动获取到与服务器通信的设置方式
                Appointment appointment = new Appointment(service);
                appointment.Subject = "test exchange meeting";
                appointment.Body = "Let's play tennis for an hour every Saturday at 15:30";
                appointment.Start = new DateTime(2013, 10, 16, 15, 30, 00);
                appointment.End = appointment.Start.AddHours(1);
                appointment.Location = "7#";

                appointment.RequiredAttendees.Add("zhengguangyan@kaifa.cn");
                appointment.RequiredAttendees.Add("shengweihu@kaifa.cn");

                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, Session["userName"].ToString());
            }
        }

        public void createmeeting()
        {
            Worker w = new Worker();
            w.SendMeetingRequest(DateTime.Now, DateTime.Now.AddHours(1), "7#", "test meeting", "test desc",
                new string[] { "shengweihu@kaifa.cn", "qifanjian@kaifa.cn", "zhengguangyan@kaifa.cn" },new string[0] ,"abc", false, "zhengguangyan", "zhengguangyan@kaifa.cn", true,"");
        }
        private string checkOnceConflict(int mtrNo, string startDate, string startTime, string weeks, string endDate, string endTime)
        {
            string[] weekdays = weeks.Split(',');//拆分星期
            DateTime sd = DateTime.Parse(startDate);
            DateTime ed = DateTime.Parse(endDate);
            using (var mme = new meetingroomManagementEntities())
            {
                //查询出所有的在本次会议开始后才结束的单次会议预定
                var query = (from bm in mme.MTR_bas_BookingManage
                             join bs in mme.MTR_bas_BookingSchedul
                                 on bm.bookingID equals bs.planId
                             where bm.Meetingroom == mtrNo && (bm.bookingState == 1 || bm.bookingState == 2) && bs.isPeriodic == false
                             && bs.meetingEndDate >= sd
                             //((sd <= bs.meetingStartDate && bs.meetingStartDate <= ed) || (sd >= bs.meetingStartDate && ed <= bs.meetingEndDate) || (sd <= bs.meetingEndDate && bs.meetingEndDate <= ed))
                             select new
                             {
                                 ssd = bs.meetingStartDate,
                                 sst = bs.startTime,
                                 sed = bs.meetingEndDate,
                                 set = bs.endTime,
                             }).ToList();
                foreach (var q in query)
                {
                    //根据时间段判断一次
                    DateTime tempSt = DateTime.Parse(startDate + " " + startTime);
                    DateTime tempEt = DateTime.Parse(startDate + " " + endTime);
                    DateTime tempQST = DateTime.Parse(startDate + " " + q.sst);
                    DateTime tempQET = DateTime.Parse(startDate + " " + q.set);
                    if (tempSt >= tempQET || tempEt < tempQST)
                    {
                        return "";
                    }
                    else
                    {
                        string dow = q.ssd.Value.DayOfWeek.ToString();//已有事件的星期
                        for (int i = 0; i < weekdays.Length; i++) {
                            if (dow == weekdays[i]) { return "系统检测到与已存在"+weekdays[i]+"的预定发生冲突"; }
                        }
                    }
                }
            }
            return "";
        }

        protected string checkOnceWithPeriodicConflict(int meetingRoomNo, string startDate, string startTime, string endDate, string endTime)
        {
            DateTime sd = DateTime.Parse(startDate);
            DateTime ed = DateTime.Parse(endDate);
            using (var mme = new meetingroomManagementEntities())
            {
                //查询出所有的在本次会议开始后才结束的会议预定
                var query = (from bm in mme.MTR_bas_BookingManage
                             join bs in mme.MTR_bas_BookingSchedul
                                 on bm.bookingID equals bs.planId
                             where bm.Meetingroom == meetingRoomNo && (bm.bookingState == 1 || bm.bookingState == 2) && bs.isPeriodic == true
                             && bs.meetingEndDate >= sd
                             select new
                             {
                                 ssd = bs.meetingStartDate,
                                 sst = bs.startTime,
                                 sed = bs.meetingEndDate,
                                 set = bs.endTime,
                                 Monday = bs.Monday,
                                 Tuesday = bs.Tuesday,
                                 Wednesday = bs.Wednesday,
                                 Thursday = bs.Thursday,
                                 Friday = bs.Friday,
                                 Saturday = bs.Saturday,
                                 Sunday = bs.Sunday
                             }).ToList();
                foreach (var q in query) {
                    //根据时间段判断一次
                    DateTime tempSt = DateTime.Parse(startDate + " " + startTime);
                    DateTime tempEt = DateTime.Parse(startDate + " " + endTime);
                    DateTime tempQST = DateTime.Parse(startDate + " " + q.sst);
                    DateTime tempQET = DateTime.Parse(startDate + " " + q.set);
                    if (tempSt >= tempQET || tempEt < tempQST)
                    {
                        continue;
                    }
                    else
                    {
                        if (q.ssd > ed)//开始日期晚于本次会议结束日期，不会冲突
                        {
                            continue;
                        }
                        else
                        {
                            if (sd.DayOfWeek.ToString() == "Monday")
                            {
                                if (q.Monday.HasValue)
                                    if (q.Monday.Value)
                                        return "系统检测到与已存在周一的预定发生冲突";
                            }
                            else if (sd.DayOfWeek.ToString() == "Tuesday" && q.Tuesday.HasValue ? q.Tuesday.Value : false) { return "系统检测到与已存在周二的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Wednesday" && q.Wednesday.HasValue ? q.Wednesday.Value : false) { return "系统检测到与已存在周三的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Thursday" && q.Thursday.HasValue ? q.Thursday.Value : false) { return "系统检测到与已存在周四的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Friday" && q.Friday.HasValue ? q.Friday.Value : false) { return "系统检测到与已存在周五的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Saturday" && q.Saturday.HasValue ? q.Saturday.Value : false) { return "系统检测到与已存在周六的预定发生冲突"; }
                            else if (sd.DayOfWeek.ToString() == "Sunday" && q.Sunday.HasValue ? q.Sunday.Value : false) { return "系统检测到与已存在周末的预定发生冲突"; }
                        }
                    }
                }
            }
            return "";
        }

        //检验周期性预定的冲突
        private string checkPeriodicConflict(int meetingRoomNo, string startDate, string startTime,
            string weekday, string endDate, string endTime)
        {
            string[] weekdays = weekday.Split(',');//拆分星期
            DateTime sd = DateTime.Parse(startDate);
            DateTime ed = DateTime.Parse(endDate);

            using (var mme = new meetingroomManagementEntities())
            {
                //查询出所有的在本次会议开始后才结束的会议预定
                var query = (from bm in mme.MTR_bas_BookingManage
                             join bs in mme.MTR_bas_BookingSchedul
                                 on bm.bookingID equals bs.planId
                             where bm.Meetingroom == meetingRoomNo && (bm.bookingState == 1 || bm.bookingState == 2) && bs.isPeriodic == true
                             && bs.meetingEndDate >= sd
                             select new
                             {
                                 ssd = bs.meetingStartDate,
                                 sst = bs.startTime,
                                 sed = bs.meetingEndDate,
                                 set = bs.endTime,
                                 Monday = bs.Monday,
                                 Tuesday = bs.Tuesday,
                                 Wednesday = bs.Wednesday,
                                 Thursday = bs.Thursday,
                                 Friday = bs.Friday,
                                 Saturday = bs.Saturday,
                                 Sunday = bs.Sunday
                             }).ToList();
                foreach (var q in query)
                {
                    //根据时间段判断一次
                    DateTime tempSt = DateTime.Parse(startDate + " " + startTime);
                    DateTime tempEt = DateTime.Parse(startDate + " " + endTime);
                    DateTime tempQST = DateTime.Parse(startDate + " " + q.sst);
                    DateTime tempQET = DateTime.Parse(startDate + " " + q.set);
                    if (tempSt >= tempQET || tempEt < tempQST)
                    {
                        return "";
                    }
                    else
                    {
                        if (q.ssd > ed)
                        {//开始日期晚于本次会议结束日期，不会冲突
                            return "";
                        }
                        if (q.ssd <= sd)  //sd 到q.sed会有冲突
                        {
                            do
                            {
                                string dow = sd.DayOfWeek.ToString();
                                for (int i = 0; i < weekdays.Length; i++)
                                {
                                    if (dow == weekdays[i]) //传入的记录中有这个
                                    {
                                        if (dow == "Monday" && q.Monday.Value) { return "系统检测到与已存在周一的预定发生冲突"; }
                                        else if (dow == "Tuesday" && q.Tuesday.Value) { return "系统检测到与已存在周二的预定发生冲突"; }
                                        else if (dow == "Wednesday" && q.Wednesday.Value) { return "系统检测到与已存在周三的预定发生冲突"; }
                                        else if (dow == "Thursday" && q.Thursday.Value) { return "系统检测到与已存在周四的预定发生冲突"; }
                                        else if (dow == "Friday" && q.Friday.Value) { return "系统检测到与已存在周五的预定发生冲突"; }
                                        else if (dow == "Saturday" && q.Saturday.Value) { return "系统检测到与已存在周六的预定发生冲突"; }
                                        else if (dow == "Sunday" && q.Sunday.Value) { return "系统检测到与已存在周末的预定发生冲突"; }
                                    }
                                }
                                sd.AddDays(1);
                            }
                            while (sd > q.sed);
                        }
                        if (q.ssd > sd)
                        {
                            //q.ssd到q.sed会有冲突
                            do
                            {
                                string dow = q.ssd.Value.DayOfWeek.ToString();
                                for (int i = 0; i < weekdays.Length; i++)
                                {
                                    if (dow == weekdays[i]) //传入的记录中有这个
                                    {
                                        if (dow == "Monday" && q.Monday.Value) { return "系统检测到与已存在周一的预定发生冲突"; }
                                        else if (dow == "Tuesday" && q.Tuesday.Value) { return "系统检测到与已存在周二的预定发生冲突"; }
                                        else if (dow == "Wednesday" && q.Wednesday.Value) { return "系统检测到与已存在周三的预定发生冲突"; }
                                        else if (dow == "Thursday" && q.Thursday.Value) { return "系统检测到与已存在周四的预定发生冲突"; }
                                        else if (dow == "Friday" && q.Friday.Value) { return "系统检测到与已存在周五的预定发生冲突"; }
                                        else if (dow == "Saturday" && q.Saturday.Value) { return "系统检测到与已存在周六的预定发生冲突"; }
                                        else if (dow == "Sunday" && q.Sunday.Value) { return "系统检测到与已存在周末的预定发生冲突"; }
                                    }
                                }
                                q.ssd.Value.AddDays(1);
                            }
                            while (q.ssd.Value > q.sed.Value);
                        }
                        if (q.sed >= ed)
                        {
                            //q.ssd到ed会有冲突
                            do
                            {
                                string dow = q.ssd.Value.DayOfWeek.ToString();
                                for (int i = 0; i < weekdays.Length; i++)
                                {
                                    if (dow == weekdays[i]) //传入的记录中有这个
                                    {
                                        if (dow == "Monday" && q.Monday.Value) { return "系统检测到与已存在周一的预定发生冲突"; }
                                        else if (dow == "Tuesday" && q.Tuesday.Value) { return "系统检测到与已存在周二的预定发生冲突"; }
                                        else if (dow == "Wednesday" && q.Wednesday.Value) { return "系统检测到与已存在周三的预定发生冲突"; }
                                        else if (dow == "Thursday" && q.Thursday.Value) { return "系统检测到与已存在周四的预定发生冲突"; }
                                        else if (dow == "Friday" && q.Friday.Value) { return "系统检测到与已存在周五的预定发生冲突"; }
                                        else if (dow == "Saturday" && q.Saturday.Value) { return "系统检测到与已存在周六的预定发生冲突"; }
                                        else if (dow == "Sunday" && q.Sunday.Value) { return "系统检测到与已存在周末的预定发生冲突"; }
                                    }
                                }
                                q.ssd.Value.AddDays(1);
                            }
                            while (q.ssd.Value > ed);
                        }
                    }
                }
            }
            return "";
        }

        [WebMethod(EnableSession = true)]
        public List<MtrData> Seek(DateTime date,string type, string address, 
            string isVIP,string userName,string orgType1,string orgType3, string capacity)
        {
            //createmeeting();   
            List<MtrData> listMtrData = new List<MtrData>();
            int cap = Convert.ToInt32(capacity);
            var mtr_resEn = new meetingroomManagementEntities();
            var query = (from a in mtr_resEn.MTR_bas_Meetingroom
                         where a.mtrDelete == true && a.mtrCapacity >= cap && a.type == type
                         && a.mtrAddress == address
                         && a.mtrCompanyRuc == orgType1
                         && (a.mtrDeptRuc == "所有部门" || a.mtrDeptRuc == orgType3)
                         select new
                         {
                             mtrID = a.mtrId,
                             mtrName = a.mtrName,
                             mtrCompanyRuc = a.mtrCompanyRuc,
                             mtrDeptRuc = a.mtrDeptRuc,
                             mtrAddress = a.mtrAddress,
                             mtrAddress1 = a.mtrAddress1,
                             type = a.type,
                             mtrCapacity = a.mtrCapacity,
                             mtrPhone = a.mtrPhone,
                             mtrPhoto = a.mtrPhoto,
                             mtrType = a.mtrType,
                             mtrFreeTime = a.mtrFreeTime,
                             mtrState = a.mtrState,
                             mtrLongestBookingDay = a.mtrLongestBookingDay,
                             mtrLongestAdvanceBookingTime = a.mtrLongestAdvanceBookingTime,
                             mtrLastUser = a.mtrLastUser,
                             mtrLastTime = a.mtrLastTime
                         }).ToList();
            if (isVIP != string.Empty)
            {
                query = query.Where(p => p.mtrType == isVIP).ToList();
            }
            //query 是符合条件的会议室
            MtrData md = new MtrData();
            foreach (var vq in query)
            {
                md = new MtrData();
                md.mtrId = vq.mtrID;
                md.mtrName = vq.mtrName;
                md.mtrCompanyRuc = vq.mtrCompanyRuc;
                md.mtrDeptRuc = vq.mtrDeptRuc;
                md.mtrAddress = vq.mtrAddress;
                md.mtrAddress1 = vq.mtrAddress1;
                md.mtrCapacity = vq.mtrCapacity;
                md.mtrPhone = vq.mtrPhone;
                md.mtrPhoto = vq.mtrPhoto;
                md.mtrType = vq.mtrType;
                md.mtrFreeTime = vq.mtrFreeTime;
                md.mtrState = vq.mtrState;
                md.mtrLongestBookingDay = vq.mtrLongestBookingDay;
                md.mtrLongestAdvanceBookingTime = vq.mtrLongestAdvanceBookingTime == 0 ? "" : vq.mtrLongestAdvanceBookingTime.ToString();//.ToString();
                md.mtrLastUser = vq.mtrLastUser;
                md.mtrLastTime = vq.mtrLastTime;
                var vk = (from k in mtr_resEn.MTR_bas_MeetingroomResources
                          join l in mtr_resEn.MTR_bas_Resources
                          on k.resId equals l.resId
                          where k.mtrId == vq.mtrID
                          select new
                          {
                              resId = k.resId,
                              resName = l.resName,
                              resIcon = l.resIcon
                          }).ToList();

                md.listMtrRes = new List<MtrRes>();
                foreach (var vks in vk)
                {
                    md.listMtrRes.Add(new MtrRes() { resId = vks.resId, resName = vks.resName, resIcon = vks.resIcon });
                }
                DateTime ds = date.AddDays(4);
                var vme = (from bm in mtr_resEn.MTR_bas_BookingManage
                           join vim in mtr_resEn.booking_View
                               on bm.bookingID equals vim.bookingID
                           where bm.Meetingroom == vq.mtrID && vim.meetingEndDate >= date && vim.meetingStartDate <= ds
                           //取消对于时间的判断&& bm.startTime >= DateTime.Now
                           select new
                           {
                               bookingID = bm.bookingID,
                               bookingType = bm.bookingType,
                               Meetingroom = bm.Meetingroom,
                               bookingPerson = bm.bookingPerson,
                               bookingTime = bm.bookingTime,
                               //endTime = bm.endTime,
                               meetingTheme = bm.meetingTheme,
                               participants = bm.participants,
                               meetingAbstract = bm.meetingAbstract,
                               specialRequestFirst = bm.specialRequestFirst,
                               specialRequestSecond = bm.specialRequestSecond,
                               bookingState = bm.bookingState,
                               cancelTime = bm.cancelTime,
                               cancelReason = bm.cancelReason,
                               useResult = bm.useResult,
                               undefine1 = bm.undefine1
                           }).ToList();
                md.listMtrEvent = new List<MtrEvent>();
                foreach (var vm in vme)
                {
                    var bs = (from bookScu in mtr_resEn.MTR_bas_BookingSchedul
                              where vm.bookingID == bookScu.planId
                              select new
                              {
                                  planId = bookScu.planId,
                                  meetingRoom = bookScu.meetingRoom,
                                  meetingStartDate = bookScu.meetingStartDate,
                                  startTime = bookScu.startTime,
                                  meetingEndDate = bookScu.meetingEndDate,
                                  endTime = bookScu.endTime,
                                  Monday = bookScu.Monday,
                                  Tuesday = bookScu.Tuesday,
                                  Wednesday = bookScu.Wednesday,
                                  Thursday = bookScu.Thursday,
                                  Friday = bookScu.Friday,
                                  Saturday = bookScu.Saturday,
                                  Sunday = bookScu.Sunday,
                                  isPeriodic = bookScu.isPeriodic,
                                  undefine1 = bookScu.undefine1,
                                  undefine2 = bookScu.undefine2
                              });
                    md.listMtrEvent.Add(new MtrEvent()
                    {
                        bookingID = vm.bookingID,
                        bookingType = vm.bookingType,
                        Meetingroom = vm.Meetingroom,
                        bookingPerson = vm.bookingPerson,
                        startTime = Convert.ToDateTime(vm.bookingTime),  //修改日期2013-9-12 15:12
                        //endTime = Convert.ToDateTime(vm.endTime),
                        meetingTheme = vm.meetingTheme,
                        participants = vm.participants,
                        meetingAbstract = vm.meetingAbstract,
                        specialRequestFirst = vm.specialRequestFirst,
                        specialRequestSecond = vm.specialRequestSecond,
                        bookingState = vm.bookingState,
                        cancelTime = vm.cancelTime,
                        cancelReason = vm.cancelReason,
                        useResult = vm.useResult,
                        BookingSchedul = bs,
                        undefine1 = vm.undefine1
                    });
                }
                listMtrData.Add(md);
            }
            //Exception es = new Exception();
            //Worker ww = new Worker();
            //ww.writeErrorMessage("0", es, "seek");
            return listMtrData;
        }
    }

    /// <summary>
    /// 符合条件的会议室拥有的资源 
    /// 投影仪
    /// 电话机
    /// </summary>
    [Serializable]
    public class MtrRes
    {
        public int resId { get; set; }
        public string resName { get; set; }
        public string resIcon { get; set; }
    }
    /// <summary>
    /// 符合条件的会议室
    /// 日期
    /// 容量
    /// IsVIP
    /// </summary>
    [Serializable]
    public class MtrData
    {
        public int mtrId { get; set; }
        public string mtrName { get; set; }
        public string mtrCompanyRuc { get; set; }
        public string mtrDeptRuc { get; set; }
        public string mtrAddress { get; set; }
        public string mtrAddress1 { get; set; }
        public int? mtrCapacity { get; set; }
        public string mtrPhone { get; set; }
        public string mtrType { get; set; }
        public string mtrFreeTime { get; set; }
        public string mtrPhoto { get; set; }
        public bool mtrState { get; set; }
        public int? mtrLongestBookingDay { get; set; }
        public string mtrLongestAdvanceBookingTime { get; set; }
        public string mtrLastUser { get; set; }
        public string mtrLastTime { get; set; }
        public string undefine1 { get; set; }
        public string undefine2 { get; set; }
        public string undefine3 { get; set; }
        public List<MtrRes> listMtrRes { get; set; }
        public List<MtrEvent> listMtrEvent { get; set; }
        //public string mtrCompany { get; set; }
        //public string mtrDeptRuc { get; set; }
        //public string mtrAddress { get; set; }
        //public string mtrAddress1 { get; set; }
        //public Nullable<int> mtrCapacity { get; set; }
        //public string mtrPhone { get; set; }
        //public string mtrType { get; set; }
        //public string mtrFreeTime { get; set; }
        //public string mtrPhoto { get; set; }
        //public bool mtrState { get; set; }
        //public Nullable<int> mtrLongestBookingDay { get; set; }
        //public string mtrLongestAdvanceBookingTime { get; set; }
        //public string mtrLastUser { get; set; }
        //public string mtrLastTime { get; set; }
        //public Nullable<bool> mtrDelete { get; set; }
        //public string undefine2 { get; set; }
        //public string undefine3 { get; set; }
    }

    [Serializable]
     public class Type{
         public string type { get; set; }
     }



    /// <summary>
    /// 符合条件的会议室已有的预定事件
    /// bookingID
    /// </summary>
    [Serializable]
    public class MtrEvent
    {
        public string bookingID { get; set; }
        public string bookingType { get; set; }
        public int Meetingroom { get; set; }
        public string bookingPerson { get; set; }
        public System.DateTime startTime { get; set; }
        public System.DateTime endTime { get; set; }
        public string meetingTheme { get; set; }
        public string participants { get; set; }
        public string meetingAbstract { get; set; }
        public string specialRequestFirst { get; set; }
        public string specialRequestSecond { get; set; }
        public Nullable<int> bookingState { get; set; }
        public string cancelPerson { get; set; }
        public Nullable<System.DateTime> cancelTime { get; set; }
        public string cancelReason { get; set; }
        public Nullable<int> useResult { get; set; }
        public Object BookingSchedul{ get; set; }
        public string undefine1 { get; set; }
    }

    [Serializable]
    public class BookingSchedul
    {
        public string planID { get; set; }
        public Nullable<int> meetingRoom { get; set; }
        public Nullable<System.DateTime> meetingStartDate { get; set; }
        public string startTime { get; set; }
        public Nullable<System.DateTime> meetingEndDate { get; set; }
        public string endTime { get; set; }
        public Nullable<bool> Monday { get; set; }
        public Nullable<bool> Tuesday { get; set; }
        public Nullable<bool> Wednesday { get; set; }
        public Nullable<bool> Thursday { get; set; }
        public Nullable<bool> Friday { get; set; }
        public Nullable<bool> Saturday { get; set; }
        public Nullable<bool> Sunday { get; set; }
        //public TimeSpan timeSpan { get; set; }
        public string undefine1 { get; set; }
        public string undefine2 { get; set; }
        //public string undefine3 { get; set; }
    }
}
